package band.wukong.practice.webservice.kh.sample08.nongen;

import band.wukong.practice.webservice.kh.sample08.*;
import band.wukong.practice.webservice.util.raw.JAXBUtil;
import com.sun.xml.ws.api.message.Headers;
import com.sun.xml.ws.developer.WSBindingProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.w3c.dom.Document;

import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.UUID;

/**
 * @author wukong(wukonggg@139.com)
 */
public class ClientTest {

    private static final Logger logger = LoggerFactory.getLogger(ClientTest.class);

    private UserService port;

    @BeforeClass
    public void init() throws MalformedURLException {
        URL wsdlUrl = new URL(UserConst.SERVICE_WSDL);
        QName serviceQName = new QName(UserConst.SERVICE_NS, UserConst.SERVICE_NAME);
        UserServiceImplService service = new UserServiceImplService(wsdlUrl, serviceQName);
        port = service.getUserServiceImplPort();
    }


    @Test
    public void list() {
        List<User> users = port.list();
        for (User u : users) {
            logger.debug("u = " + u);
        }
    }

    @Test
    public void add() throws UserException_Exception {
        addHeader(); // 客户端处理header
        User u = random();
        port.add(u);
        logger.debug("u = " + u);
    }

    /**
     * 重复添加用户
     *
     * @throws UserException_Exception
     */
    @Test(expectedExceptions = UserException_Exception.class, expectedExceptionsMessageRegExp = "用户已存在")
    public void addFailed01() throws UserException_Exception {
        addHeader(); // 客户端处理header
        User u = random();
        port.add(u);
        port.add(u);
    }

    /**
     * 需要权限控制.
     */
    @Test(expectedExceptions = UserException_Exception.class, expectedExceptionsMessageRegExp = "该功能需权限控制")
    public void addFailed02() throws UserException_Exception {
        User u = random();
        port.add(u);
    }

    @Test
    public void login() throws UserException_Exception {
        User u = null;
        try {
            u = port.login("wukong", "nwims666");
        } catch (UserException_Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
        logger.debug("u = " + u);
    }

    /**
     * 需要权限控制.
     */
    @Test
    public void delete() throws UserException_Exception {
        addHeader(); // 客户端处理header
        User u = random();
        try {
            port.add(u);
            port.delete(u.getName());
        } catch (UserException_Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 需要权限控制.
     */
    @Test(expectedExceptions = UserException_Exception.class, expectedExceptionsMessageRegExp = "该功能需权限控制")
    public void deleteFailed01() throws UserException_Exception {
        try {
            port.delete("wukong");
        } catch (UserException_Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    private User random() {
        String passwd = UUID.randomUUID().toString();
        String name = passwd.substring(passwd.length() - 12 , passwd.length());
        return new User(name, passwd);
    }

    private void addHeader() {
        // 1. 将一个对象转换为xml，通过JAXB
        LicenceInfo licenceInfo = new LicenceInfo();
        licenceInfo.setRegisterUser(new User("admin", "nwims666"));
        QName qName = new QName(UserConst.SERVICE_NS, "licenceInfo");  // 这样就不用去改（总是会自动生成的）LicenseInfo了
        JAXBElement<LicenceInfo> elmt = new JAXBElement<>(qName, LicenceInfo.class, licenceInfo);

        // 2. 转换为DOM
        Document doc = null;
        try {
            doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        } catch (ParserConfigurationException e) {
            logger.error(e.getMessage());
            throw new RuntimeException("Client Error");
        }
        JAXBUtil.marshallByJAXBElement(elmt, false, LicenceInfo.class, doc);

        // 3. 通过Headers.create方法完成header的添加
        WSBindingProvider wsb = (WSBindingProvider) port;
        wsb.setOutboundHeaders(Headers.create(doc.getDocumentElement()));
    }

}
